package com.xoa.controller.workflow;

import com.ibatis.common.resources.Resources;
import com.xoa.dao.WFE.WFEFormTypeMapper;
import com.xoa.dao.work.WorkMapper;
import com.xoa.dao.workflow.FlowTypeModelMapper;
import com.xoa.model.workflow.FlowFormType;
import com.xoa.model.workflow.FlowTypeModel;
import com.xoa.util.HtmlUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.wrapper.BaseWrappers;
import com.xoa.util.page.PageParams;
import freemarker.core.ReturnInstruction;
import org.apache.ibatis.annotations.Param;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by gsb on 2017/8/15.
 */
@Controller
@RequestMapping("/flowRunPage")
public class FlowRunPageController {

    @Resource
    private FlowTypeModelMapper flowTypeModelMapper;

    @Resource
    private WFEFormTypeMapper wfeFormTypeMapper;

    @Autowired
    WorkMapper workMapper;

    @RequestMapping("/queryFlowRun")
    public String showPage(){
        return "app/workflow/flowRun/queryFlowRun";

    }
    @RequestMapping("/allsearch")
    public String allsearch(){
        return "app/workflow/flowRun/allsearch";

    }

    @RequestMapping("/allSearchList")
    public String allSearchList(){
        return "app/workflow/flowRun/allSearchList";
    }

    static String reg = "(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|" + "(\\b(select|update|and|or|delete|insert|trancate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute)\\b)";

    static Pattern sqlPattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);//表示忽略大小写
    /**
     *1.按后台设置的规则改造工作查询 2020/4/15
     * JarvisHao  flowId设计的流程号
     */
    @RequestMapping("/queryFlowRuns")
    @ResponseBody
    public BaseWrappers queryFlowRunList(Integer flowId, Integer page, Integer pageSize, Boolean useFlag, String condition){
        BaseWrappers wrappers = new BaseWrappers();
        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(useFlag);
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);

        // 数据查询参数map
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("tableName", "flow_data_" + flowId);// 查询的表

        page = (page - 1) * pageSize;
        map.put("page", page);// 分页
        map.put("pageSize", pageSize);

        String mappingSqlStr = "";
        if (!StringUtils.checkNull(condition)) {
            String[] split = condition.split(",");
            for (String s : split) {
                String[] split1 = s.split("=");
                if (split1.length > 1) {// 防止传空 报错
                    mappingSqlStr += " and " + split1[0] + " like " + "'%" + split1[1] + "%'";
                }
            }
        }
        //mappingSqlStr = mappingSqlStr.substring(0,mappingSqlStr.length()-4);
        boolean sqlValid = isSqlValid(mappingSqlStr);
        if (false == sqlValid){
            wrappers.setFlag(false);
            wrappers.setMsg("参数存在非法字符");
            return wrappers;
        }
        map.put("where",mappingSqlStr);// 查询的条件

        List<Map<String, String>> maps = workMapper.selectflowRunPage(map);
        int counut = workMapper.selectflowRunPagecounts(map);
        wrappers.setDatas(maps);
        wrappers.setTotal(counut);
        return wrappers;
    }


    public static boolean isSqlValid(String str) {
        Matcher matcher = sqlPattern.matcher(str);
        if (matcher.find()) {
            System.out.println("参数存在非法字符，请确认："+matcher.group());//获取非法字符：or
            return false;
        }
        return true;
    }

    /**
     *查询当前流程（新工作查询）返回的查询条件  和列表显示
     * @param flowId
     *
     * @return
     */
    @RequestMapping("/queryFlowId")
    @ResponseBody
    public BaseWrappers queryFlowId(Integer flowId){
        BaseWrappers wrappers = new BaseWrappers();
        // 数据查询参数map
        Map<String,Object> map = new HashMap<String,Object>();
        List<Object> zong = new ArrayList<Object>();
        List<Object> zong2 = new ArrayList<Object>();
        FlowTypeModel flowTypeModel = flowTypeModelMapper.queryOneObject(flowId);
        String[] split1 = flowTypeModel.getQueryField().split(",");//查询条件字段定义
        for (String s:split1){
            List<String> list = new ArrayList<String>();
            String[] tiao = s.split("\\|\\|");
            List<FlowFormType> allFlowForm = wfeFormTypeMapper.getFrombyFlowId(flowId);//获取控件类型
            FlowFormType flowFormType = allFlowForm.get(0);
            Document document = HtmlUtil.getDom(flowFormType.getPrintModel());
            String documentDataType = HtmlUtil.getDocumentDataType(document, tiao[1].toString());
            list.add(documentDataType==null?"":documentDataType);//控件类型
            list.add(tiao[0].toString());//条件名称
            list.add(tiao[1].toString());//条件data
            zong.add(list);
        }
        String[] split2 = flowTypeModel.getQueryListField().split(",");//查询列表字段定义
        for (String s:split2){
            List<String> list = new ArrayList<String>();
            String[] zhi = s.split("\\|\\|");
            list.add(zhi[0]);//条件名称
            list.add(zhi[1]);//条件data
            zong2.add(list);
        }
        if ("0".equals(flowTypeModel.getQueryNewYn())){ // 0不新建  1新建
            map.put("YN",0);
        }else {
            map.put("YN",1);
        }

        List<Object> hou = new ArrayList<Object>();
        hou.add(zong);
        hou.add(zong2);
        hou.add(map);
        Map<String,Object> maps = new HashMap<String,Object>();
        maps.put("flowName",flowTypeModel.getFlowName());
        hou.add(maps);
        wrappers.setObject(flowTypeModel.getFlowName());
        wrappers.setDatas(hou);
        wrappers.setFlag(true);
        wrappers.setMsg("ok");
        return wrappers;
    }

    public FlowTypeModelMapper getFlowTypeModelMapper() {
        return flowTypeModelMapper;
    }

    public void setFlowTypeModelMapper(FlowTypeModelMapper flowTypeModelMapper) {
        this.flowTypeModelMapper = flowTypeModelMapper;
    }
}
